import Vue from 'vue'
import App from './App'
import uView from 'uview-ui';
import md5 from './utils/md5.js';
import eventBus from 'utils/EventBus.js';  
//引入vuex
import store from './store'
//全局注入w-loading组件
import wLoading from "@/components/w-loading/w-loading.vue";
Vue.component('w-loading',wLoading)


Vue.prototype.$store = store

// 保证首页的 onLoad 在 onLaunch 之后执行
Vue.prototype.$onLaunched = new Promise(resolve => {
    Vue.prototype.$isResolve = resolve
})
Vue.use(uView);

Vue.config.productionTip = false


App.mpType = 'app'

const app = new Vue({
    ...App
})

// http拦截器，将此部分放在new Vue()和app.$mount()之间，才能App.vue中正常使用
import httpInterceptor from '@/common/http.interceptor.js'
Vue.use(httpInterceptor, app)

// http接口API集中管理引入部分
import httpApi from '@/common/http.api.js'
Vue.use(httpApi, app)

app.$mount()

//------------------------------------------------------JMessage start----------------------------------------------------------
var JMessage=require('./static/jmessage/jmessage-wxapplet-sdk-1.4.3.min.js')
var jim = new JMessage({
       // debug : true
    });

	
var random_str = 'lksdjflk134kljdfkljd';//随机字符串
var timestamp = Date.parse(new Date()).toString();//时间戳

jim.init({
            "appkey"    : "c1b05213e3b0d22b353a4216",
            "random_str": random_str,
            "signature" : md5.md5('appkey=c1b05213e3b0d22b353a4216&timestamp='+timestamp+'&random_str='+random_str+'&key=0696c2ff847dd598853ea434'),
            "timestamp" : timestamp,
			"flag":1
        }).onSuccess(function(data) {
			console.log('极光IM初始化成功');
			const userInfo = uni.getStorageSync("userInfo");
			if(userInfo){
				//登录IM账号
				jim.login({
				    'username' : userInfo.imUser,
				    'password' : userInfo.imPwd,
					'is_md5':false
				}).onSuccess(function(data) {
					console.log('极光IM登录成功');
					App.globalData.jmLogin = true
					eventBus.$emit('listenLogin');
				}).onFail(function(data){
				  //同上
				  console.log('极光IM登录出错-->',data);
				});
			}
          //TODO
        }).onFail(function(data) {
          console.log('极光IM初始化出错-->',data);
        });
//解析消息	
function parseMsg(messages){
	messages.forEach(msg=>{
		let realMsgType = msg.content.msg_type;
		if(msg.msg_type==3 && msg.content.msg_type != "custom"){
			let content = {};
			//加入消息同步机制后自己发的消息也会同步回来,因此这里需要判断发送人是不是自己,如果发送人是自己则应该把聊天记录存在对方的会话中
			const userInfo = uni.getStorageSync("userInfo");
			let uid = userInfo.imUser === msg.content.from_id ? msg.content.target_id : msg.content.from_id;
			if(msg.content.msg_type == "text"){//文本消息
				content = {"content":msg.content.msg_body.text};
				//解析穿搭资料 提示消息 穿搭方案等消息
				let extras = msg.content.msg_body.extras;
				if(extras){//存在附加参数,表面为特殊消息
					let msgType = extras.msgType;
					if(msgType=='5'){//穿搭资料
						let photo = extras.photo;
						if(photo){
							photo = photo.indexOf("http")==0 ? photo : 'https://posting.imguangguang.com/'+photo;
						}
						let msgExtras = {'title':'穿搭资料','content':content['content'],'photo':photo,'buyerUserId':extras.buyerUserId,'orderId':extras.orderId}
						content["extras"] = msgExtras;
						realMsgType = 'card';
					}else if(msgType=='7' || msgType=='8'){
						let name = extras.name;
						if(name==null){
							name = '穿搭方案';
						}
						let introduce = extras.introduce;
						if(introduce==null){
							introduce = '这是根据你提供的穿搭资料为你量身定做的穿搭方案';
						}
						let photo = extras.photo;
						if(photo){
							photo = /* photo.startWith('http') ? photo : */'https://posting.imguangguang.com/'+photo;
						}
						let msgExtras = {'title':name,'content':introduce,'photo':photo,'schemeId':extras.schemeId}
						content["extras"] = msgExtras;
						realMsgType = 'card';
					}else if(msgType=='4'){//带跳转功能
						if(userInfo.imUser === msg.content.from_id){//提示类的后台同步消息 忽略
							return;
						}
						//设置富文本提示
						let msgExtras = {'jumpType':'wearData'}//跳转类型为查看穿搭资料
						content['content'] = content['content'];
						// content['content'] = '[{"name": "div","children: [ {"type": "text","text": "'+content['content']+'","attrs": {"style": "color:#999999;"} },{"type": "text","text": "去设置","attrs": {"style": "color:red;"}} }]';
						content["extras"] = msgExtras;
						realMsgType = 'tips_jump';
					}else if(msgType=='6'||msgType=='9'||msgType=='10'||msgType=='11'||msgType=='12'||msgType=='13'){
						if(userInfo.imUser === msg.content.from_id){//提示类的后台同步消息 忽略
							return;
						}
						realMsgType = 'tips';
					}
				}
				//修改会话最后一条消息内容
				jim.updateConversation({'username' : uid,'extras':{'msg':msg.content.msg_body.text}});
			}else if(msg.content.msg_type == "voice"){//语音 
				content = {"url":msg.content.msg_body.media_id,"length":msg.content.msg_body.duration};//语音时长单位为秒, 需到聊天页面做格式化处理
				//修改会话最后一条消息内容
				jim.updateConversation({'username' : uid,'extras':{'msg':'[语音]'}});
			}else if(msg.content.msg_type == "file" && msg.content.msg_body.extras.type=='voice'){ //web版不支持发语音/改用文件代替
				realMsgType = 'voice';
				content = {"url":msg.content.msg_body.media_id,"length":msg.content.msg_body.extras.length};//语音时长单位为秒, 需到聊天页面做格式化处理
				//修改会话最后一条消息内容
				jim.updateConversation({'username' : uid,'extras':{'msg':'[语音]'}});
			}else if(msg.content.msg_type == "image"){//图片
				content = {"url":msg.content.msg_body.media_id,"w":msg.content.msg_body.width,"h":msg.content.msg_body.height};
				//修改会话最后一条消息内容
				jim.updateConversation({'username' : uid,'extras':{'msg':'[图片]'}});
			}
			//重新组装消息
			let item = {"id":msg.msg_id,"uid":msg.content.from_id,"receiver_id":msg.content.target_id,"time":msg.ctime_ms,"type":realMsgType,"msg":content};

			console.log("im账号-->"+uid);
			let history = uni.getStorageSync(uid);//聊天记录
			if(history){
				//检查是否已经存在这条消息,如果存在则忽略
				var isExist = false;
				for (let i=0; i<history.length; i++) {
				    const x = history[i];
					if(x.id == item.id){
						isExist = true;
						break;
					}
				} 
				if(isExist){
					return;
				}
				history.push(item);
			}else{
				history = [item];
			}
			uni.setStorageSync(uid, history);
			//把图片真正的路径查询出来
			if(content.url){
				jim.getResource({'media_id' : content['url'],})
				.onSuccess(function(data) {
				     item.msg.url = data.url;
				     eventBus.$emit('onNewMsg', item);
				 }).onFail(function(data) {
				 });
			}else{
				eventBus.$emit('onNewMsg', item);
			}
		}else if(msg.msg_type==3 && msg.content.msg_type == "custom"){//自定义消息
			let customMsg = msg.content.msg_body.text;
			let customMsgObj = JSON.parse(customMsg);
			if(customMsgObj.msgType == 0){//新订单
				eventBus.$emit('onNewOrder', customMsgObj);
				console.log("onNewOrder",customMsgObj);
			}else if(customMsgObj.msgType == 1){//搭配师接了我发布的订单
				eventBus.$emit('onOrderReceived', customMsgObj);
				console.log("onOrderReceived",customMsgObj);
			}
		}
	});
}

jim.onMsgReceive(function(data) {//有新消息 使用eventbus分发事件   msg_type=3 单聊  聊天室消息和群聊消息忽略
	console.log("新消息", data);
	var messages = data.messages;
	parseMsg(messages);
	let unReadCount = uni.getStorageSync("unReadCount");
	if(messages.unread_msg_count>0){
		if(unReadCount){
			unReadCount = unReadCount + messages.unread_msg_count;
		}else{
			unReadCount = messages.unread_msg_count;
		}
		uni.setStorageSync("unReadCount", unReadCount);
	}
});

jim.onSyncConversation(function(data) {//离线消息
   console.log("离线消息", data);
   let unReadCount = uni.getStorageSync("unReadCount");
   data.forEach(item=>{
	   //离线消息检测未读消息数  如果未读消息数是0   则忽略它----    如果不忽略的话每次登录后消息都会同步,且未读消息总数会出错
	   if(item.unread_msg_count>0){
		   parseMsg(item.msgs);
		   if(unReadCount){
		   		   unReadCount = unReadCount + item.unread_msg_count;
		   }else{
		   		   unReadCount = item.unread_msg_count;
		   }
	   }
   });
   uni.setStorageSync("unReadCount", unReadCount);
});

// // 监听已读回执----没有效果
// jim.onMsgReceiptChange((data) => {
//     console.log("已读回执", data)
// });
// // 监听同步的已读回执，用作补偿
// jim.onSyncMsgReceipt((data) => {
//     console.log("已读回执", data)
// });

jim.onDisconnect(function(){//断线重连机制
	const userInfo = uni.getStorageSync("userInfo");
	App.globalData.jmLogin = false;
	let isInit = jim.isInit();
	console.log("断线重连检测极光是否初始化", isInit);
	if(isInit){//这个地方原本的写法是断线检测后重新登录, 后经常发现有提示没有初始化的日志,因此加个是否初始化判断,如果未初始化则再次初始化后再登录
		//登录IM账号
		jim.login({
		    'username' : userInfo.imUser,
		    'password' : userInfo.imPwd
		}).onSuccess(function(data) {
			console.log('极光IM登录成功');
			App.globalData.jmLogin = true
			eventBus.$emit('listenLogin');
		}).onFail(function(data){
		  //同上
		  console.log('极光IM登录出错-->',data);
		});
	}else{
		let random_str = 'lksdjflk134kljdfkljd';//随机字符串
		let timestamp = Date.parse(new Date()).toString();//时间戳
		jim.init({
		            "appkey"    : "c1b05213e3b0d22b353a4216",
		            "random_str": random_str,
		            "signature" : md5.md5('appkey=c1b05213e3b0d22b353a4216&timestamp='+timestamp+'&random_str='+random_str+'&key=0696c2ff847dd598853ea434'),
		            "timestamp" : timestamp,
					"flag":1
		        }).onSuccess(function(data) {
					console.log('断线重连极光IM重新初始化成功');
					const userInfo = uni.getStorageSync("userInfo");
					if(userInfo){
						//登录IM账号
						jim.login({
						    'username' : userInfo.imUser,
						    'password' : userInfo.imPwd,
							'is_md5':false
						}).onSuccess(function(data) {
							console.log('极光IM登录成功');
							App.globalData.jmLogin = true
							eventBus.$emit('listenLogin');
						}).onFail(function(data){
						  //同上
						  console.log('极光IM登录出错-->',data);
						});
					}
		          //TODO
		        }).onFail(function(data) {
		          console.log('断线重连极光IM重新初始化出错-->',data);
		    });
	}
});

export default {//先在export外定义变量，然后export
   jim
};
//------------------------------------------------------JMessage end----------------------------------------------------------